import java.applet.Applet;
import java.awt.Button;
import java.awt.Desktop;
import java.awt.FlowLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;


public class GameLauncher extends Applet{

	public static String serverip;
	public static String serverport;
	public static String playername;
	public String batchName = "launchbatch.bat";
	public String gameFolder = "MarioArena\\";
	public String textFileName = "gamedata.txt";

	public GameLauncher() {
		//AttemptLaunch("testip", "testport", "testname"); //ONLY USE FOR DEBUGGING. COMMENT BEFORE EXPORT.
	}

	/**
	 * Attempts to launch the mario arena game with the given arguments.
	 * @param ip Ip of gameserver.
	 * @param port Port of gameserver.
	 * @return Returns either the path to the user's Appdate/Roaming folder with additional data, or an error string.
	 */
	public String AttemptLaunch(String ip, String port, String name){
		serverip = ip;
		serverport = port;
		playername = name;

		@SuppressWarnings("unchecked")
		String appdataPath = (String) AccessController.doPrivileged(
				new PrivilegedAction() {
					public Object run() {
						String extraData = "|Received arguments: " + serverip + " and " + serverport + " and " + playername;

						String appdataFolder = System.getenv("APPDATA") + "\\";
						String filePath = appdataFolder + gameFolder + textFileName;
						String foundPath = "";

						//Retrieve executable path from textfile.
						foundPath = getPathToGameExecutable(filePath);

						if(foundPath != "" && foundPath != null)
						{
							try {
								executeBatchLaunching(appdataFolder + gameFolder, foundPath);
							} catch (Exception e) {
								return "ERROR#Could not open file: " + foundPath + ". Please make sure you allowed java to make changed to your computer.";
							}
							return appdataFolder + extraData;
						}
						else return "ERROR#Game executable could not be found. Please start the game manually and try again.";
					}
				});
		
		if(appdataPath == null || appdataPath == "")
			return "ERROR#Cannot retrieve app data path.";
		else return appdataPath;
	}

	/**
	 * Reads text file containing the path to the game executable and returns the path.
	 * @param fileWithPathToExe
	 * @return Returns path to executable.
	 */
	public String getPathToGameExecutable(String fileWithPathToExe){
		try {
			BufferedReader reader = new BufferedReader(new FileReader(fileWithPathToExe));
			String pathToExecutable = reader.readLine();
			reader.close();
			return pathToExecutable;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * Creates a batch file with the path to the game executable. The batch file is then executed and removed afterwards.
	 * @param batStorageFolder
	 * @param pathToGameExe
	 */
	public void executeBatchLaunching(String batStorageFolder, String pathToGameExe){
		try {
			//create the batch file
			File file = new File(batStorageFolder + this.batchName);
			FileWriter fwrite = new FileWriter(file);
			fwrite.write("start " + pathToGameExe + " " + serverip + " " + serverport + " " + playername + "\n");
			fwrite.write("DEL %0");
			fwrite.flush();
			fwrite.close();

			//execute the batch
			System.out.println("Created " + file.getAbsolutePath());
			File batchFile = new File(batStorageFolder + this.batchName);
			Desktop.getDesktop().open(batchFile);

			//Alternatives:
			//Desktop.getDesktop().open(file);
			//Process process = new ProcessBuilder(foundPath, serverip, serverport).start();
			//Runtime runtime = Runtime.getRuntime();
			//Process process = runtime.exec(foundPath + " param11111 param22222");		
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
